package com.ms.p2p.interceptor;


import com.ms.common.utils.AppContext;
import com.ms.p2p.Constants;
import com.ms.p2p.entity.member.Member;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

public class MemberWapLoginVerifyInterceptor implements HandlerInterceptor {
	public static final String loginUrl = "/wap/member/common/login";


	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response, Object handler) throws Exception {

		//User user =getCurrentUser();
		Member principal = (Member) AppContext.getSessionAttr(Constants.PRINCIPAL_SESSION_NAME);
		if(principal != null){

			return true;
		}


		//	CookieUtils.removeCookie(request, response, LOGIN_MEMBER_USERNAME_COOKIE_NAME);
		if (AppContext.isAjax(request)) {
			response.addHeader("loginStatus", "accessDenied");
			response.sendError(403);
			return false;
		}
		if (request.getMethod().equalsIgnoreCase("GET")){
			String s1 = request.getRequestURL().toString();
			Object oldUrl = request.getAttribute("oldUrl");
			if(oldUrl != null){
				s1 = oldUrl.toString();
			}
			if(request.getQueryString() != null){
				s1 = s1 + "?" + request.getQueryString();
			}
			StringBuilder sb = new StringBuilder("/wap/member/common/login?");
			response.sendRedirect(sb.append("redirectUrl").append("=").append(URLEncoder.encode(s1, "UTF-8")).toString());
		} else {
			response.sendRedirect("/wap/member/common/login");
		}
		return false;
	}



	@Override
	public void afterCompletion(HttpServletRequest request,
								HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}


	@Override
	public void postHandle(HttpServletRequest request,
						   HttpServletResponse response, Object handler,
						   ModelAndView modelAndView) throws Exception {
		clearCache(response);
	}

	/**
	 * 清除缓存
	 */
	private void clearCache(HttpServletResponse response){
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);
	}

}
